package com.ktjiaoyu.controller;

import com.alibaba.fastjson2.JSON;
import com.ktjiaoyu.entity.Supplier;
import com.ktjiaoyu.entity.SysRole;
import com.ktjiaoyu.entity.SysUser;
import com.ktjiaoyu.service.SupplierService;
import com.ktjiaoyu.service.SysRoleService;
import com.ktjiaoyu.service.UploadService;
import com.ktjiaoyu.utils.Constants;
import com.ktjiaoyu.utils.Page;
import io.micrometer.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/main/supplier")
public class SupplierController extends BaseController{
    private static final Logger logger = LoggerFactory.getLogger(SupplierController.class);

    @Autowired
    private SupplierService supplierService;

    @Autowired
    @Qualifier("toLocalUploadService")
    private UploadService uploadService;
    @Autowired
    private SysRoleService sysRoleService;


    @RequestMapping("/page")
    public String page(Model  model, Supplier condition,
                       @RequestParam(value = "pageNo" , defaultValue = "1") Integer pageNum,
                       @RequestParam(value = "pageSize" , defaultValue = "5") Integer pageSize){
        Page<Supplier> page = null;
        try {
            //查询供应商分页数据
            page = supplierService.findPage(condition, pageNum, pageSize);
            //查询所有供应商信息
            List<Supplier> supplierList = supplierService.findAll();
            model.addAttribute("pageInfo", page);
            model.addAttribute("supplierList", supplierList);
            model.addAttribute("condition", condition);
        } catch (Exception e) {
            logger.error("SupplierController中的page方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "supplier/page";
    }

    //跳转到save.jsp页面
    @GetMapping("/save")
    public String toSave(Model model) {
        List<Supplier> supplierList = null;
        try {
            supplierList = supplierService.findAll();
            model.addAttribute("supplierList", supplierList);
            //会显示数据时需要Supplier对象，这里空对象避免错误
            model.addAttribute("supplier", new Supplier());
        }catch (Exception e){
            logger.error("SupplierController中的toSave方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }


    //保存或修改数据接口 添加
    @PostMapping("/save")
    public String doSave(@ModelAttribute Supplier supplier, @RequestParam("bizPic") MultipartFile bizPicPath){
        //允许上传的图片扩展名
        String[] allowImageExt = new String[]{"png", "jpg", "jpeg", "gif" , "bmp"};
        try {
            //上传营业执照
            if (!bizPicPath.isEmpty()){
                String bizPicPathPath = uploadService.uploadFile(bizPicPath, allowImageExt);
                supplier.setBizPicPath(bizPicPathPath);
            }
            if (supplier.getId() == null){
                //无主键则新增
                supplier.setCreatedTime(new Date());
            }else {
                //有主键则更新
                supplier.setUpdatedTime(new Date());
            }
            //保存或修改数据
            boolean ok = supplierService.saveOrUpdate(supplier);
            if (ok){
                return redirect("/main/supplier/page");
            }
        }catch (Exception e){
            logger.error("SupplierController中的doSave方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    //查询用户信息并跳转到查看页面
    @GetMapping("/view/{id}")
    public String view(@PathVariable("id") Long id, Model model) {
        Supplier supplier = null;
        try {
            supplier = supplierService.getById(id);
            model.addAttribute("supplier", supplier);
        } catch (Exception e) {
            logger.error("SysUserController中的view方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "supplier/view";
    }

    //查询供应商信息并跳转到修改页面
    @GetMapping("/edit")
    public String toEdit(@RequestParam("id") Long id, Model model) {
        Supplier supplier = null;
        try {
            supplier = supplierService.getById(id);
            model.addAttribute("supplier", supplier);
        } catch (Exception e) {
            logger.error("SupplierController中的toEdit方法执行错误", e);
            throw new RuntimeException(e);
        }
        return "supplier/save";
    }

    //删除供应商信息
    @DeleteMapping("/del/{id}")
    @ResponseBody
    public Map<String, Object> del(@PathVariable("id") Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean ok = supplierService.deleteById(id);
            if (ok){
                result.put("code",200);
                result.put("message", "删除成功");
            }else {
                result.put("code",500);
                result.put("message", "删除失败");
            }
        } catch (Exception e) {
            logger.error("SupplierController中的del方法执行错误", e);
            result.put("code", 500);
            result.put("message", "服务器错误：" + e.getMessage());
        }
        return result;
    }

    @ResponseBody
    @GetMapping("/supCodeExist")
    public String supCodeExist(@RequestParam("supCode") String supCode) {
        logger.info("检查编码是否存在：{}", supCode);
        HashMap<String, Object> resultMap = new HashMap<>();
        if (StringUtils.isEmpty(supCode)){
            resultMap.put("exist", 0);
        }else{
            try{
                Supplier supplier = supplierService.findByAccount(supCode);
                if (supplier != null){
                    //用户名已存在
                    resultMap.put("exist", 1);
                }else{
                    resultMap.put("exist", 0);
                }
            } catch (Exception e) {
                resultMap.put("error", "验证账号时发生错误");
                logger.error("验证账号出错", e);
            }
        }
        return JSON.toJSONString(resultMap);
    }
}
